import request from '@utils/request'
import { APIParams, APIResult } from '@utils/request/type'
import { DeviceDTO, DeviceSaveForm, TbDevice, UserDeviceRoleDTO } from '@/api/entity/device'
import { ElTreeData } from '@typings/element-plus'
import { ObjectUtil } from '@utils/object-util'
import { TbGroup } from '@/api/entity/scene'
import { ServerEnum } from '@/api/enum/server'

// TODO 查询

/**
 * 分页查询
 * @param params
 */
export const getDeviceListByPageAPI = (params: APIParams.Page<{
  // 场景id
  groupId: string,
  // 模糊查询
  q: string,
  // 设备状态 0-离线 1-在线
  status: boolean
}>) => request.post<APIResult.Page<TbDevice[]>>(ServerEnum.System + '/device/page', params)

/**
 * 获取设备列表 - 包含分享来的设备
 */
export const getDeviceListAPI = () => request.get<APIResult<DeviceDTO[]>>(ServerEnum.System + '/device/list')

/**
 * 获取设备列表 - 仅自己的设备
 */
export const getDeviceListByCurrentUserAPI = () => request.get<APIResult<DeviceDTO[]>>(ServerEnum.System + '/device/userDevice')

/**
 * 获取设备列表 - 自己和管理的设备（自己 + 可管理）
 */
export const getDeviceListByAdminRoleAPI = () => request.get<APIResult<DeviceDTO[]>>(ServerEnum.System + '/deviceRole/adminDeviceRole')

/**
 * 根据id获取设备
 * @param params
 */
export const getDeviceByIdAPI = (params: { id: string }) => request.get<APIResult<DeviceDTO>>(ServerEnum.System + '/device/view/' + params.id)

/**
 * 根据id获取设备详情
 * @param params
 */
export const getDeviceDetailByIdAPI = (params: { id: string }) => request.get<APIResult<DeviceDTO>>(ServerEnum.System + '/device/detail/' + params.id)

/**
 * 根据场景id获取设备列表
 * @param params
 */
export const getDeviceListBySceneIdAPI = (params: { id: string }) => request.get<APIResult<DeviceDTO[]>>(ServerEnum.System + '/device/getByGroupId/' + params.id)

/**
 * 获取没有关联场景的设备
 */
export const getDeviceListOfNotSceneAPI = () => request.post<APIResult<DeviceDTO[]>>(ServerEnum.System + '/device/selectNoGroup2Device')

/**
 * 获取场景和设备层级列表
 */
export const getDeviceListBySceneAPI = () => request.get<APIResult<TbGroup[]>>(ServerEnum.System + '/device/getByGroup')

/**
 * 获取场景和设备层级列表 - 格式化树数据
 */
type ElTreeDataType = ElTreeData<{ isDevice?: boolean, data?: DeviceDTO }>
export const getDeviceBySceneTreeAPI = async () => {
  // 获取默认场景
  const getDefaultScene = new Promise<ElTreeDataType[]>((resolve) => {
    getDeviceListOfNotSceneAPI().then((res) => {
      res.result().then((rdata) => {
        const data = rdata.data || []
        resolve(data.map(item => ({
          isDevice: true,
          value: item.id,
          label: item.deviceName,
          key: 'D' + item.id,
          data: item
        })))
      }).catch(() => resolve([]))
    }).catch(() => resolve([]))
  })
  return Promise.all([
    getDefaultScene,
    getDeviceListBySceneAPI()
  ]).then((response) => {
    const res = response[1]
    const { data, code } = res.data
    if (code === 200) {
      const resultData: ElTreeDataType[] = [
        { key: 'S0', value: null, label: '默认场景', isDevice: false, children: response[0] }
      ]
      if (data.length) {
        ObjectUtil.deepForEach<TbGroup | DeviceDTO, ElTreeDataType, ElTreeDataType>(data, (item, resolve, parent) => {
          const children = parent?.children || resultData
          const isDevice = !!parent
          const _item = { isDevice, value: item.id } as ElTreeDataType
          if (isDevice) {
            const dItem = item as DeviceDTO
            _item.key = 'D' + dItem.id
            _item.data = dItem
            _item.label = dItem.deviceName
          } else {
            const dItem = item as TbGroup
            _item.key = 'S' + dItem.id
            _item.children = []
            _item.label = dItem.name
            dItem.deviceDTOList && resolve(dItem.deviceDTOList, _item)
          }
          children.push(_item)
        })
      }
      res.data.data = resultData as any
    }
    return res as unknown as APIResult.Response.Data<ElTreeDataType[]>
  })
}

/**
 * 获取当前用户下所有的设备权限
 */
export const getDeviceRoleListByCurrentUserAPI = () => request.get<APIResult<UserDeviceRoleDTO[]>>(ServerEnum.System + '/deviceRole/userDeviceRole')

// TODO 编辑
/**
 * 添加设备
 * @param params
 */
export const addDeviceAPI = (params: DeviceSaveForm) => request.post(ServerEnum.System + '/device/add', params)

/**
 * 编辑设备
 * @param params
 */
export const editDeviceAPI = (params: DeviceSaveForm) => request.post(ServerEnum.System + '/device/edit', params)

/**
 * 删除设备
 * @param params
 */
export const delDeviceAPI = (params: { id: string }) => request.get(ServerEnum.System + '/device/delete/' + params.id)

// TODO 控制

/**
 * 写入设备变量 - 控制
 * @param params
 */
export const controlDeviceVariableAPI = (params: {
  // 设备ID
  deviceId: string
  // 控制参数
  param: string
  // 变量ID
  variableId: string
}) => request.post(ServerEnum.System + '/device/control', params)

/**
 * 同一个网关下验证设备名是否重复 true-重复
 * @param params
 */
export const checkDeviceNameRepeatAPI = (params: {
  // 设备ID
  id: string
  // 设备名称
  deviceName: string
  // 网关id
  gatewayId: string
}) => request.post<APIResult<boolean>>(ServerEnum.System + '/device/vfDeviceName', params)
